package com.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil {

	private static final int FIRST_DAY = Calendar.MONDAY;
	
	public static int getIntDate(Date date) {
		return getIntDate(date, null);
	}


	public static String getStartWeek(){
		Calendar calendar = Calendar.getInstance();
		while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
			calendar.add(Calendar.DATE, -1);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(calendar.getTime());
	}
	
	public static String getEndWeek(){
		Calendar calendar = Calendar.getInstance();
		while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
			calendar.add(Calendar.DATE, -1);
		}
		calendar.add(Calendar.DATE, 6);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(calendar.getTime());
	}
	
	
	   /**
	    * 日期格式为yyyy-MM-dd HH:mm
	    */
	    private static SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US);
	    /**
	    * 日期格式为yyyy-MM-dd
	    */
	    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US);
	    
	    /**
	    * 当前季度的开始时间
	    */
	    public static Date getCurrentQuarterStartTime() {
	        Calendar c = Calendar.getInstance();
	        int currentMonth = c.get(Calendar.MONTH) + 1;
	        Date now = null;
	        try {
	            if (currentMonth >= 1 && currentMonth <= 3)
	                 c.set(Calendar.MONTH, 0);
	             else if (currentMonth >= 4 && currentMonth <= 6)
	                 c.set(Calendar.MONTH, 3);
	             else if (currentMonth >= 7 && currentMonth <= 9)
	                 c.set(Calendar.MONTH, 6);
	             else if (currentMonth >= 10 && currentMonth <= 12)
	                 c.set(Calendar.MONTH, 9);
	             c.set(Calendar.DATE, 1);
	             now = datetimeFormat.parse(dateFormat.format(c.getTime()));
	         } catch (Exception e) {
	             e.printStackTrace();
	         }
	         return now;
	     }
	     /**
	      * 当前季度的结束时间
	      */
	     public static Date getCurrentQuarterEndTime() {
	         Calendar c = Calendar.getInstance();
	         int currentMonth = c.get(Calendar.MONTH) + 1;
	         Date now = null;
	         try {
	             if (currentMonth >= 1 && currentMonth <= 3) {
	                 c.set(Calendar.MONTH, 2);
	                 c.set(Calendar.DATE, 31);
	             } else if (currentMonth >= 4 && currentMonth <= 6) {
	                 c.set(Calendar.MONTH, 5);
	                 c.set(Calendar.DATE, 30);
	             } else if (currentMonth >= 7 && currentMonth <= 9) {
	                 c.set(Calendar.MONTH, 8);
	                 c.set(Calendar.DATE, 30);
	             } else if (currentMonth >= 10 && currentMonth <= 12) {
	                c.set(Calendar.MONTH, 11);
	                c.set(Calendar.DATE, 31);
	            }
	            now = datetimeFormat.parse(dateFormat.format(c.getTime()));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return now;
	    }
	
	     
	   

	     /**
	      * 当月第一天
	      * @return
	      */
	     public static String getFirstDay() {
	         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	         Calendar calendar = Calendar.getInstance();
	         Date theDate = calendar.getTime();
	         
	         GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
	         gcLast.setTime(theDate);
	         gcLast.set(Calendar.DAY_OF_MONTH, 1);
	         String day_first = df.format(gcLast.getTime());
	         StringBuffer str = new StringBuffer().append(day_first);
	         return str.toString();

	     }
	     
	     /**
	      * 当月最后一天
	      * @return
	      */
	     public static String getLastDay() {
	         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	         Calendar calendar = Calendar.getInstance();
	         Date theDate = calendar.getTime();
	         String s = df.format(theDate);
	         StringBuffer str = new StringBuffer().append(s);
	         return str.toString();

	     }
	public static int getIntDate(Date date, String sysformat) {
		if (sysformat == null || sysformat.equalsIgnoreCase("Fams")) {
			SimpleDateFormat df = new SimpleDateFormat("yyMMdd");
			String dateStr = df.format(date);
			return Integer.parseInt(dateStr);
		}
		return 0;
	}

	public static long getTimeMillisSequence() {

		long nanoTime = System.nanoTime()+(long)(Math.random()*100);
		return nanoTime;
	}

	public static String getVersionSequence() {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmm");
		String dateStr = df.format(new Date());
		return dateStr;
	}
	
	
	public static String getVersionSequenceDate() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		String dateStr = df.format(new Date());
		return dateStr;
	}
	
	public static Date getDate(Integer intDate, Object intTime) {
		if (intTime instanceof Short) {
			return getDate(intDate, intTime);
		} else if (intTime instanceof Integer) {
			return getDate(intDate, intTime);
		}
		return null;
	}

	public static Date getDate(Integer intDate, Integer intTime) {
		return getDate(intDate, intTime, null);
	}

	public static Date getDate(Integer intDate, Integer intTime,
			String sysformat) {
		if (sysformat == null || sysformat.equalsIgnoreCase("Fams")) {
			SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");
			try {
				return df.parse(getDateStr(6, intDate)
						+ getTimeStr(9, intTime.intValue() * 10));
			} catch (ParseException pe) {
				pe.printStackTrace();
			}
		}
		return null;
	}

	public static Date getDate(Integer intDate, Short intTime) {
		return getDate(intDate, intTime, null);
	}

	public static Date getDate(Integer intDate, Short intTime, String sysformat) {
		if (sysformat == null || sysformat.equalsIgnoreCase("Fams")) {
			SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmm");
			try {
				return df.parse(getDateStr(6, intDate)
						+ getTimeStr(4, intTime.intValue()));
			} catch (ParseException pe) {
				pe.printStackTrace();
			}
		}
		return null;
	}

	public static String getDateStr(int maxLength, Integer intDate) {
		if (intDate != null && intDate.intValue() != 0) {
			StringBuffer dateStrBuf = new StringBuffer("");
			if (intDate.toString().length() < maxLength) {
				for (int i = 0; i < maxLength - intDate.toString().length(); i++) {
					dateStrBuf.append("0");
				}
			}
			dateStrBuf.append(intDate.toString());
			return dateStrBuf.toString();
		} else {
			return "000101";
		}
	}

	public static String getTimeStr(int maxLength, int intTime) {
		if (intTime != 0) {
			StringBuffer dateStrBuf = new StringBuffer("");
			if (Integer.toString(intTime).length() < maxLength) {
				for (int i = 0; i < maxLength
						- Integer.toString(intTime).length(); i++) {
					dateStrBuf.append("0");
				}
			}
			dateStrBuf.append(Integer.toString(intTime));
			return dateStrBuf.toString();
		} else {
			StringBuffer zeroStrBuf = new StringBuffer();
			for (int i = 0; i < maxLength; i++) {
				zeroStrBuf.append("0");
			}
			return zeroStrBuf.toString();
		}
	}

	public static long getIntTime(Date date) {
		return getIntTime(date, null);
	}

	public static int getIntTime(Date date, String sysformat) {
		if (sysformat == null || sysformat.equalsIgnoreCase("Fams")) {
			SimpleDateFormat df = new SimpleDateFormat("HHmmssSSS");
			String timeStr = df.format(date);
			// timeStr += "00";
			return Integer.parseInt(timeStr) / 10;
		}
		return 0;
	}

	public static String getFormatDate(Date date, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	public static String getFormatDate(String date, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		Date newdate = null;
		try {
			newdate = df.parse(date);
		} catch (Exception ex) {
		}

		return df.format(newdate);
	}

	public static String getFullBeginDateStr(String date) {
		return date + " 00:00:00.000";
	}

	public static String getFullEndDateStr(String date) {
		return date + " 23:59:59.999";
	}

	// public static void main(String[] args) {
	// System.out.println(getDate(new Integer("010101"),new
	// Short("0101"),null));
	// System.out.println( getDate(new Integer("51103"),new Integer("6454699"))
	// );
	// System.out.println(currdate);
	// }
	public static final Date convertStringToDate(String aMask, String strDate)
			throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat(aMask);
		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	public static final String convertDateToString(String parrten, Date date) {
		SimpleDateFormat df = null;
		String dStr = null;
		if (parrten != null && !parrten.equals("")) {
			df = new SimpleDateFormat(parrten);
		} else {
			df = new SimpleDateFormat("yyyy-MM-dd");
		}
		if (date == null) {
			dStr = df.format(new Date());
		} else {
			dStr = df.format(date);
		}
		return dStr;
	}

	public static final String getHalfYear(int month) {
		Date d = new Date();
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(2, month);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public static final String getsubMonth(int month) {
		Date d = new Date();
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
		gc.setTime(d);
		gc.add(2, month);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}
	
	
	public static final String getMonth(int month) {
		Date d = new Date();
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(2, month);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public static final String getMonthOfDate(String currentDate,int month){
		Date d = new Date();
		try {
			d = new SimpleDateFormat("yyyy-MM-dd").parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(2, month);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}
	
	
	public static final String getMonthOfDate(String currentDate,int month,int days){
		Date d = new Date();
		try {
			d = new SimpleDateFormat("yyyy-MM-dd").parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(2, month);
		gc.add(5, days);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}
	
	public static final String getDayOfDate(String currentDate,int days){
		Date d = new Date();
		try {
			d = new SimpleDateFormat("yyyy-MM-dd").parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(5, days);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}
	
	/**
	 * 获取当前的时间字符串
	 * 
	 * @return
	 */
	public static String getStringNow() {
		return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
	}

	public static String getNowDateByFormat(String strFormat) {
		if (strFormat == null || strFormat.equals(""))
			strFormat = "yyyy-MM-dd HH:mm:ss";
		try {

			Date now = new Date();
			SimpleDateFormat format = new SimpleDateFormat(strFormat);
			return format.format(now);

		} catch (Exception e) {
			return "";
		}
	}

	public static String getReportDays(int days) {
		Date d = new Date();
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		gc.setTime(d);
		gc.add(5, days);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	
	public static final String getTableMonth(int month) {
		Date d = new Date();
		Calendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
		gc.setTime(d);
		gc.add(2, month);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}
	
	public static String getQuarters() {
		Date d = new Date();
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(3, 1);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	/**
	 * get last day of month
	 * 
	 * @param month
	 * @return
	 */
	public static int getEndDaysOfMonth() {
		Calendar cla = Calendar.getInstance();
		int dayNum = cla.getActualMaximum(Calendar.DAY_OF_MONTH);
		return dayNum;
	}

	public static String getDays(Date d, int days) {
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		gc.setTime(d);
		gc.add(5, days);
		gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc
				.get(Calendar.DATE));
		return sf.format(gc.getTime());
	}

	public static String getCurrentYear() throws Throwable {

		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String currentDate = format.format(new Date());
		return currentDate;
	}

	public static String getCurrentDate(){

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String currentDate = format.format(new Date());
		return currentDate;
	}
	

	public static String getCurrentDate1(){

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String currentDate = format.format(new Date());
		return currentDate;
	}

	
	/**
	 * 
	 * @param date1 <String>
	 * @param date2 <String>
	 * @return int
	 * @throws ParseException
	 */
	public static int getMonthSpace(String date1, String date2){

		int result = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		try {
			c1.setTime(sdf.parse(date1));
			c2.setTime(sdf.parse(date2));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		result = c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH);

		return result == 0 ? 1 : Math.abs(result);

	}

	
	public static boolean isCurrentDate(Date inputDate){

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String currentDate = format.format(new Date());
		
		String execDate = getFormatDate(inputDate,"yyyy-MM-dd");
		if(execDate.equals(currentDate)){
			return true;
		}
		return false;
	}
	
	/**
	 * 功能：判断是否是当前日期
	 * 
	 * @param daysOfMonth
	 * @return
	 */
	public static boolean isCrrentDay(String daysOfMonth) {
		boolean isFlag = false;
		String[] days = daysOfMonth.split("\\$");
		if (days != null && days.length > 0) {
			GregorianCalendar gc = new GregorianCalendar();
			String day = String.valueOf(gc.get(Calendar.DATE));
			for (int i = 0; i < days.length; i++) {
				if (day.equals(days[i])) {
					return true;
				}
			}
		}
		return isFlag;
	}

	/**
	 * 判断是否为周末
	 * 
	 * @return
	 */
	public static boolean isWeek() {
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date bdate;
		try {
			bdate = format1.parse(getCurrentDate());
			Calendar cal = Calendar.getInstance();
			cal.setTime(bdate);
			if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
					|| cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				return true;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return false;
	}

	public static int dayForWeek(String dateTime) throws Throwable {
		return 0;
	}

	public static void main(String[] args) {
		/*
		 * Calendar cla =Calendar.getInstance();
		 * System.out.println(cla.getActualMaximum(Calendar.DAY_OF_MONTH));
		 */
		// String startDate ="2008-10-14";
		try {
				System.out.println(getMonthOfDate("2015-03-09",2,-1));
		} catch (Throwable e) {
			e.printStackTrace();
		}
		/*
		 * try { Date data1 =DateUtil.convertStringToDate("yyyy-MM-dd",
		 * startDate); System.out.println(DateUtil.getHalfYear(-2)); } catch
		 * (ParseException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */

		// System.out.println(startDate.substring(5, 7));
		// System.out.println(Integer.parseInt(DateUtil.getNowDateByFormat("MM")));

	}

}
